import Carousel, { ICarousel } from '../models/Carousel';
import { Request, Response } from 'express';
import upload from '../middlewares/upload';
import moment from 'moment'

// 增加轮播图
export const addCarousel = async (req: Request, res: Response) => {
    upload.single('image')(req, res, async (error: any) => {
        if (error) {
            return res.status(500).json({ message: error.message });
        }

        try {
            // 创建新的轮播图对象
            const newCarouselData = {
                ...req.body,
                image: req.file ? req.file.path : '', // 获取上传的图片路径
                createdAt: moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: moment().format('YYYY-MM-DD HH:mm:ss')
            };

            const newCarousel = new Carousel(newCarouselData);
            await newCarousel.save();
            res.status(201).json({
                status: 'ok',
                message: '新增轮播图成功！',
                data: newCarousel
            });
        } catch (error: any) {
            res.status(500).json({ message: error.message });
        }
    });
};

// 删除轮播图
export const deleteCarousel = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const carousel = await Carousel.findByIdAndDelete(id);
        if (!carousel) {
            return res.status(404).json({
                message: '轮播图未找到'
            });
        }
        res.json({
            status: 'ok',
            message: '轮播图删除成功'
        });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 更新轮播图
export const updateCarousel = async (req: Request, res: Response) => {
    upload.single('image')(req, res, async (error: any) => {
        if (error) {
            return res.status(500).json({
                status: 'error',
                message: '图片上传失败',
                data: error.message
            });
        }

        try {
            const { _id } = req.body;
            let updateData = req.body;

            // 如果有新的图片上传，则更新图片路径
            if (req.file) {
                updateData.image = req.file.path;
            } else {
                delete updateData.iamge
            }

            const updatedCarousel = await Carousel.findByIdAndUpdate(_id, updateData, { new: true });
            const newCarousel = new Carousel({
                ...updateCarousel, ...{
                    updatedAt: moment().format('YYYY-MM-DD HH:mm:ss')
                }
            })
            if (!updatedCarousel) {
                return res.status(404).json({
                    status: 'error',
                    message: '轮播图未找到',
                    data: null
                });
            }

            res.json({
                status: 'ok',
                message: '轮播图更新成功！',
                data: updatedCarousel
            });
        } catch (error: any) {
            res.status(500).json({
                status: 'error',
                message: '更新轮播图失败',
                data: error.message
            });
        }
    });
};

// 查询单个轮播图
export const getCarouselById = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const carousel = await Carousel.findById(id);
        if (!carousel) {
            return res.status(404).json({ message: '轮播图未找到' });
        }
        res.json(carousel);
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 分页查询所有轮播图
export const getCarousels = async (req: Request, res: Response) => {
    try {
        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 10;
        const skipIndex = (page - 1) * limit;
        const carousels = await Carousel.find().skip(skipIndex).limit(limit);
        const total = await Carousel.countDocuments();
        res.json({
            total,
            page,
            limit,
            data: carousels
        });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};
